import asyncio
import random
import re
from datetime import date, datetime
from io import BytesIO

from PIL import Image
from loguru import logger
from lxml import etree
from rapidocr import RapidOCR

from .http import client
from .wx import async_push

# 同一包内  最好相对导入 这样可以少写一些字符  也可以绝对导入
# 不在同一包内 可以使用绝对导入    相对导入只能使用在子包

headers = {
	"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1"
}
engine = RapidOCR(params={"Global.use_det": False, "Global.use_cls": False})
sent_set = set()


@logger.catch
async def visa_status_change():
	# try:
	#
	# except Exception as e:
	# 	logger.exception(e)
	if not await find_message_list():
		_, v_code_response = await asyncio.gather(index(), v_code())
		logger.info(v_code_response)
		code, flag = v_code_response
		if flag:
			await login(code)
			# web(client)
			await find_message_list()


async def index():
	response = await client.get("https://tisp.utourworld.com/")
	logger.info(f"index {response.status_code=}")


async def web():
	response = await client.get("/web/index.jsp")
	logger.info(f"web {response.status_code=}")


async def find_message_list():
	# https://tisp.utourworld.com/findList?cat=%E7%AD%BE%E8%AF%81%E7%8A%B6%E6%80%81%E5%8F%98%E6%9B%B4&sta=0
	# https://tisp.utourworld.com/findMessageList
	params = {"cat": "签证状态变更", "sta": 0, "pageNo": 1, "pageSize": 10}
	response = await client.get("https://tisp.utourworld.com/findList", params=params)
	logger.info(f"find_message_list {response.status_code=}")
	if not response.is_success:
		logger.error("find_message_list response is not success")
		logger.error(f"header = {response.headers}")
		return False

	html = etree.HTML(response.content)
	# tables = html.xpath("//div[@class='frameBody']//table")
	# 海象运算符    if语句不产生新的作用域
	if not (tables := html.xpath("//div[@class='frameBody']//table")):
		logger.info("no table...........")
		return False
	table = tables[0]
	table_headers = []
	if header_rows := table.xpath(".//tr[th]"):
		# 取第一个包含th的tr作为表头
		header_row = header_rows[0]
		table_headers = [th.text.strip() for th in header_row.xpath(".//th")]
	data_rows: list[list[str]] = []
	for row in table.xpath(".//tr"):
		# 跳过表头行（如果已经处理过）
		if row.xpath(".//th"):
			continue
		# 提取当前行的所有td文本
		if cells := ["" if not td.text else td.text.strip() for td in row.xpath(".//td[not(contains(@style, 'display: none'))]")]:
			data_rows.append(cells)
	logger.info(f"result = {[table_headers] + data_rows}")
	condition_set = set()
	for _, summary, sender, date_time, *_ in data_rows:
		change_time = datetime.strptime(date_time, "%Y-%m-%d %H:%M:%S")
		if change_time.date() == date.today() and summary.find("指纹通知") > 0:
			logger.info(f"{summary=}")
			condition_set.add(f"{summary}_{sender}")

	global sent_set
	if candidate_result := condition_set - sent_set:
		await asyncio.gather(*[async_push("签证状态变更", candidate_data) for candidate_data in candidate_result])
		sent_set = condition_set
	return True


async def v_code():
	response = await client.get(f"https://tisp.utourworld.com/createValidateCode?flag={random.random()}")
	logger.info(f"v_code {response.status_code=}")
	if response.is_success:
		img = Image.open(BytesIO(response.content))
		return ocr_result(img), True
	return None, False


async def login(code: str):
	data = {"empCode": "112169", "password": "wqm1992527", "captcha": code, "activationCode": "", "verificationSta": "0"}
	response = await client.post("https://tisp.utourworld.com/login", data=data)
	logger.info(f"login {response.status_code=}")
	if response.is_redirect:
		logger.error(f"header = {response.headers}")


def ocr_result(image):
	result = engine(image)
	matches = re.findall(r"[a-zA-Z0-9]", "".join(result.txts))  # 匹配单个字母或数字
	result = "".join(matches)
	return result
